package q1_volatile_test;

/**
 *volatile禁止指令重排demo
 */
public class SingletonDemo {

    /**
     * 不加volatile，多线程环境下可能会发生指令重排，虽然机率很低，但是无法保证线程安全
     */
    private static volatile SingletonDemo instance = null;

    private SingletonDemo(){
        System.out.println(Thread.currentThread().getName() + "\t 我是构造方法" );

    }

    //DCL(Double Check Lock 双端检锁机制)
    public static SingletonDemo getInstance(){
        if(instance == null){
            synchronized (SingletonDemo.class){
                if(instance == null){
                    instance = new SingletonDemo();
                }
            }
        }

        return instance;
    }

    public static void main(String[] args) {

        for (int i = 1; i <= 10; i++) {
            new Thread(()->{
                SingletonDemo.getInstance();
            }, "A" + i).start();
        }

    }
}
